package com.service.single.util;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * @Author: 一休
 * @Date: 2024/9/10
 */
public class ConcurrentStar {
    private static final String COOKIE = ".Cnblogs.AspNetCore.Cookies=CfDJ8KL9kPW-LSFBi_9YdTzcC09JGMA7uydZP4549VWARXM8QqVR4LXcNUGDHRhw22jbv9uTGmGmZT4rvJeN6spMdwqTyJmvBJxDdoVKTbPBm8AryNKvd6BulzdmSasfiSFLdL4hvHAd6GFPw4V-6tsHD68CRx-kSxtV1tijDO4wDk8CU9jYh1VWbO7s-DHWS05LPhzrmAOJhomZR7xAQ7ywD_qJNN8yvNFWbKrFOgVuusRrdBYlJOScqSiMwC7FTL7Kzg8-GG_wS5x8-GRQN4EtuRtIXZlp0mbTyV57NfAX0rKfjqTvlKNiSWmBclL2XNJ2Q07EWhbbmrs0Kv80qIG5YU9NyFWzdJVPGXm3Qa-fWcGSy4hIYXMhi-CeNL05nnRwsMTPJObOi6A9TZz-bJ_hJkWqZTNedozORfPzcsXPriDEuS19zmfwuaClexLz3Q2JTViNYdNdmGHYI9J8aEVDWjx6-NTeRNpWkoUDfwi1KdEZ-5UT9_pEvC_0vyFl2JmP-RCrLC1NI3eBk2f0HmQ8UiZsAB_M2jxKF8sGwah0qdl1hIDOw39fGmrWaBiazqTIPez9WOqH8ruIqZ5AxpZxcW5RSguaK7MsvAVMmm8L9Rig";
    private static final String REQUEST_WITH = "XMLHttpRequest";

    private static final Integer NUMBER = 4;


    /**
     * 删除指定的星星
     *
     * @param ingId 要删除的星星的ID
     *              该ID用于标识特定的星星资源，是删除操作的关键参数。
     */
    public static void del(String ingId) {
        // 构建删除请求的URL
        String delUrl = "https://ing.cnblogs.com/ajax/ing/del";
        // 发送POST请求，提交删除表单，包含ingId参数，并设置请求头信息
        String delBody = HttpRequest.post(delUrl).form("ingId", ingId).header("cookie", COOKIE).header("x-requested-with", REQUEST_WITH).execute().body();
        // 打印删除操作的响应内容
        System.out.println("删除：" + delBody);
    }

    private static String all() {
        String allUrl = "https://ing.cnblogs.com/ajax/ing/GetIngList?IngListType=all&PageIndex=1&PageSize=10&Tag=&_=1728530513959";
        String allBody = HttpRequest.get(allUrl).header("Content-Type", "application/json").header("Accept-Encoding", "gzip, deflate, br").header("Connection", "keep-alive").header("cookie", COOKIE).header("accept", "text/plain, */*; q=0.01").header("x-requested-with", REQUEST_WITH).execute().body();
        Document document = Jsoup.parse(allBody);
        Element bdo = document.getElementsByTag("bdo").first();
        String text = bdo.text();
        System.out.println(text);
        return text;

    }

    /**
     * 发布星星
     * <p>
     * 向指定URL发布内容，并检查发布的内容是否包含星星。
     *
     * @param content 要发布的内容
     */
    private static void publish(String content) {
        // 构建发布请求的URL和请求体
        String publishUrl = "https://ing.cnblogs.com/ajax/ing/Publish";
        String[] emoji = new String[]{"🍎", "🍌", "🍉", "🍐", "🍇", "🍓", "🫐", "🍈", "🍒", "🍑", "🥭"};
        try {
            ExecutorService executor = Executors.newFixedThreadPool(NUMBER);
            for (int i = 0; i < NUMBER; i++) {
                String emojiStr = emoji[i];
                executor.submit(() -> {
                    String publishBody = HttpRequest.post(publishUrl).form("content", "[新闻]" + emojiStr + content).form("publicFlag", 1).header("cookie", COOKIE).execute().body();
                    // 打印发布结果
                    System.out.println("发布：" + publishBody + " " + LocalDateTime.now());
                });
            }
            executor.shutdown();
            Thread.sleep(1500);
        } catch (Exception e) {
            e.printStackTrace();
        }
        checkStar(content);
    }


    /**
     * 校验网络上的图片是否包含星星，如果不包含则删除该图片，并发布新内容。
     * <p>
     * 参数:
     * content - 要发布的新内容。
     * <p>
     * 返回值: 无
     */
    public static void checkStar(String content) {
        // 构造请求URL并发送GET请求，获取网页内容
        String requestUrl = "https://ing.cnblogs.com/ajax/ing/GetIngList?IngListType=My&PageIndex=1&PageSize=10&Tag=&_=1685670088011";
        String body = HttpRequest.get(requestUrl).header("Content-Type", "application/json").header("Accept-Encoding", "gzip, deflate, br").header("Connection", "keep-alive").header("cookie", COOKIE).header("accept", "text/plain, */*; q=0.01").header("x-requested-with", REQUEST_WITH).execute().body();
        // 使用Jsoup解析获取到的HTML内容
        Document document = Jsoup.parse(body);
        Elements elementLis = document.getElementsByTag("li");
        List<Element> elements = elementLis.stream().filter(e -> e.select("div[class=feed_body]").size() > 0).limit(NUMBER).collect(Collectors.toList());
        Boolean flag = false;
        for (Element element : elements) {
            Elements divFeedBody = element.select("div[class=feed_body]");
            Element feedBody = divFeedBody.get(0);
            Elements imgs = feedBody.getElementsByTag("img");
            Element img = imgs.get(0);
            // 打印图片信息并提取标题
            System.out.println("img: " + img.toString());
            String title = img.attr("title");
            // 检查标题中是否包含特定关键词，不包含则删除图片并发布新内容
            if (StringUtils.isNotBlank(title)) {
                boolean contains = title.contains("星") || title.contains("庆祝") || title.contains("国庆");
                if (!contains) {
                    String id = feedBody.attr("id");
                    String[] array = id.split("_");
                    String value = array[2];
                    System.out.println("删除：" + value);
                    del(value);
                }
                if (contains) {
                    flag = true;
                }
            }
        }
        try {
            Thread.sleep(300000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!flag) {
            publish(content);
        }

    }

    public static void touTiao() {
        String url = "https://www.toutiao.com/hot-event/hot-board/?origin=toutiao_pc&_signature=_02B4Z6wo00101r.r7TAAAIDB7RTNKwXFep6.z-mAAMmNEIL21bHsc2DytviNK6DWjHhQrROlIboL0uY16O3wvohrSV-1zPe08jGejq73A2XdFO.a2BL0tFZ06e9Zezu9.4yT.mmqjcpaVkKQ7c";
        String body = HttpRequest.get(url).execute().body();
        JSONObject result = JSONObject.parseObject(body);
        List<Object> array = new ArrayList<>(result.getJSONArray("data"));
        List<String> list = array.stream().map(item -> {
            JSONObject jsonObject = (JSONObject) item;
            String title = jsonObject.getString("Title");
            String link = jsonObject.getString("Url");
            return title + link;
        }).collect(Collectors.toList());
        list.forEach(item -> {
            ConcurrentStar.publish(item);
        });
    }

    public static void hupu(String type) {
        String url = "https://sbmy.fun/api/hotSearch/queryByType?type=" + type;
        String body = HttpRequest.get(url).execute().body();
        JSONObject result = JSONObject.parseObject(body);
        List<Object> array = new ArrayList<>(result.getJSONObject("data").getJSONArray("hotSearchDTOList"));
        array.forEach(item -> {
            JSONObject jsonObject = (JSONObject) item;
            String title = jsonObject.getString("hotSearchTitle");
            String link = jsonObject.getString("hotSearchUrl");
            ConcurrentStar.publish(title + link);
        });
    }

    public static void text() {
        for (int i = 0; i < 100; i++) {
            System.out.println("第 " + i + " 次发布");
            String text = ConcurrentStar.all();
            ConcurrentStar.publish(text);
        }

    }

    public static void main(String[] args) throws Exception {
        ConcurrentStar.touTiao();

    }
}
